//
//  WBMainController.swift
//  CustomWeiBo
//
//  Created by laiqiang on 21/5/9.
//  Copyright © 2021年 laiqiang. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBMainController: UITabBarController {
    
    fileprivate var timer:Timer?

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupChildCotroller()
        
        setupComposeBtn()
        
        //FIXME:
//        setupTimer()
        
        setupNewfeatureView()
        
        delegate = self
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin(n:)), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
    }
    
    deinit {
        //销毁定时器
        timer?.invalidate()
        NotificationCenter.default.removeObserver(self)
    }
    
    //重写支持界面方向方法，
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        
        return .portrait
//        lreturn .andscape
        
        //竖屏:portrait肖像画(小窗口),横屏:风景画andscape(大范围)
    }
    
    @objc fileprivate func userLogin(n:Notification){
        
        var when = DispatchTime.now()
        //判断 n。object是否有值，如果有值，提示重新登录
        if n.object != nil {
            
            SVProgressHUD.setDefaultMaskType(.gradient)
            SVProgressHUD.showInfo(withStatus: "用户登录超时，请重新登录")
            when = DispatchTime.now() + 2
        }
        
        DispatchQueue.main.asyncAfter(deadline: when) {
            
            //登录控制器 一般 和 uinavgation控制器连用
            let vc = WBOAuthViewController()
            let nv = UINavigationController.init(rootViewController: vc)
            self.present(nv, animated: true) {}
            print("登录通知～～～～～")
        }

    }
    
    lazy var composeButton = UIButton(frame: CGRect(x: 0, y:4, width:64, height: 40))
    
    @objc func composeButtonAction(){
        
        print("写微博")
        
        let vc = WBBasController()
        
        let  nv = UINavigationController(rootViewController: vc)

        present(nv, animated: true) { }
        
    }
}

extension WBMainController {

    fileprivate func setupNewfeatureView() {
        
        
        //没有登录啥都不敢
        if !WBNetworkingManager.share.userLogin {
            return
        }
        
        //1.检查版本 是否更新
        
        
        //2.更新：显示新特性
        let v = isNewfeature ? WBNewFeatrure.newFeatrure() : WBWelcomeView.welcomeView()
        
        //3.添加视图
        view.addSubview(v)
    }
    
    //计算型属性：版本信息 Bundle versions string, short
    /**
     上架一次 版本号增加
      主版本号，次版本号 ，修订版本号
     主版本号：大的修改
     次版本号：小的修改，函数，方法变化
     修订版本号：bug的修复，用户没有影响
     */
    fileprivate var isNewfeature: Bool {
        
        //当前版本  Bundle Versions String, short
//        print(Bundle.main.infoDictionary)
        let current_version = (Bundle.main.infoDictionary?["CFBundleShortVersionsString"] as? String) ?? ""

        //获取“版本数据的沙盒”路径
        let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0]
        let version_path = (path as NSString).appendingPathComponent("version")
        
        //获取保存的版本号［document  ，放入user default较好］
        let sandbox_version = try?String(contentsOfFile: version_path)
        
        //保存当前版本号
        try?current_version.write(toFile: version_path, atomically: true, encoding: .utf8)
        
        //两个版本是否一致,不相等时，显示新特性
//        return current_version != sandbox_version
        
        return current_version == sandbox_version
    }
}

extension WBMainController : UITabBarControllerDelegate{

    //将要选择 TabBarItem
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
       
        print("将要切换到：\(viewController)")
        //获取viewController的索引
        let idx = childViewControllers.index(of: viewController)
        
        //在首页，再次点击了首页 的item  存在未读数据  滚到顶部，加载数据
        if selectedIndex == 0 && idx == selectedIndex {
            
            print("点击首页")
            //获取控制器
            let nav = childViewControllers[0] as! WBNavController
            let vc = nav.childViewControllers[0] as! WBHomeController
            
            
            let barHeight = vc.navgationbar.bounds.height
            vc.tableView?.setContentOffset(CGPoint.init(x: 0, y: -(barHeight)), animated: true)
            
            //加载新的网络数据,需要延迟加载，刷新界面(因为 tableview动画时，不能刷新，会错乱)，延迟后动画结束才回正常
            DispatchQueue.main.asyncAfter(deadline:DispatchTime.now() + 1 , execute: { 
                
                vc.loaddata()//滚动动画结束后，加载数据，刷新界面
            })
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
        }
        
        //判断目标控制器是否是UIViewController
        return !viewController.isMember(of: UIViewController.self)
    }
}

//时钟相关
extension WBMainController {

    fileprivate func setupTimer(){
    
        timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    @objc fileprivate func updateTimer (){
        //FIXME:
        return
        
        if !WBNetworkingManager.share.userLogin {
            
            return
        }
    
        //测试未读的数据
        WBNetworkingManager.share.unreadCount { (count) in
            
            print("有\(count)新的微博")
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}

extension WBMainController {
    
    func setupComposeBtn(){
        
        tabBar.addSubview(composeButton)
        composeButton.backgroundColor = UIColor.init(red:255/255.0, green:72/255.0, blue:145/255.0, alpha: 1.0)
        
        
        let count = CGFloat(childViewControllers.count)
        let w = tabBar.bounds.width / count
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
        let fonttex = NSAttributedString(string: "+", attributes: [NSFontAttributeName:UIFont.systemFont(ofSize:55),
                                                                   NSForegroundColorAttributeName:UIColor.white,
                                                                   NSBaselineOffsetAttributeName:NSNumber.init(value:2)])
        composeButton.setAttributedTitle(fonttex, for: .normal)
        
        composeButton.addTarget(self, action:#selector(composeButtonAction), for: .touchUpInside)
    }

    //设置所有子控制器
    func setupChildCotroller(){
        
        //在bundle 加载默认的json
        //JSON转换NSData对象-再到
        //沙盒中取出数据
        let dire = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        
        let jsonpath = (dire as NSString).appendingPathComponent("main.json")
        
        var data = NSData(contentsOfFile: jsonpath)
        
        if data == nil {
            
            let path = Bundle.main.path(forResource:"main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        
        guard let array = try! JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String:Any]]
        else {
            return
        }
        
        
        

//        let array: [[String:Any]] = [["clsName":"WBHomeController","title":"首页","imgName":"home",
//                                      "visitorInfo":["imgName":"","message":"哈哈"]],
//                                     
//                                     ["clsName":"WBMsgController","title":"消息","imgName":"multi_store",
//                                      "visitorInfo":["imgName":"visitor_msg","message":"登录后发现更多消息，哈哈"]],
//                                     
//                                     ["clsName":"UIViewController"],
//                                     
//                                     ["clsName":"WBDiscoverController","title":"发现","imgName":"shopping_cart",
//                                      "visitorInfo":["imgName":"visitor_home","message":"登录后发现关注了谁，哈哈"]],
//                                     
//                                     ["clsName":"WBProfileController","title":"我","imgName":"mine",
//                                      "visitorInfo":["imgName":"visitor_head","message":"登录后发现我，哈哈"]]
//                     ]
        
        //数组转成json 序列化，转成plish文件，直观 需要有文件了才能写入
        //try?
        //获取需要的内容，需要考虑数据是否存在，是否拆包
//        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted]) as Data
//        let str = String(data: data, encoding: String.Encoding.utf8)!
//        try! str.write(toFile: "/Users/laiqiang/Desktop/NewWeiBo/CustomWeiBo/CustomWeiBo/Class/View/Main/main.json", atomically: true, encoding: String.Encoding.utf8)
        
        
        var arrayc = [UIViewController]()
        for dic in array {
            
            arrayc.append(buildController(dic: dic))
        }
        
        viewControllers = arrayc
    }
    
    //字典创建控制器
    private func buildController(dic:[String:Any])->UIViewController{
        //字典内容
        guard let clsname = dic["clsName"] as? String,
            let title = dic["title"] as? String,
            let imageName = dic["imgName"] as? String,
        let vistorInfo = dic["visitorInfo"] as? [String:String],
            let cls = NSClassFromString(Bundle.main.namespace + clsname) as? WBBasController.Type
        else {
            let newvc = UIViewController()
            newvc.view.backgroundColor = UIColor.orange
            return newvc
        }
        
        //创建视图控制器
        let vc = cls.init()
        vc.title = title
        //设置访客字典数据
        vc.visitorInfo = vistorInfo;
        
        //图片
        vc.tabBarItem.image = UIImage(imageLiteralResourceName:imageName + "_unactive")
        vc.tabBarItem.selectedImage = UIImage(imageLiteralResourceName:imageName + "_active").withRenderingMode(.alwaysOriginal)
        
        //标题字体颜色,系统默认12号，修改narmal
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.init(red:255/255.0, green:72/255.0, blue:145/255.0, alpha: 1.0)],for: .selected)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12)], for: .normal)
        
        //这里也会调用 push方法，将
        let nav = WBNavController(rootViewController: vc)

        return nav
    }

}

struct MySnail {
    
    // 字典或者数组 转 JSON
    static func dataTypeTurnJson(element:AnyObject) -> String {
        
        let jsonData = try! JSONSerialization.data(withJSONObject: element, options: JSONSerialization.WritingOptions.prettyPrinted)
        
        let str = String(data: jsonData, encoding: String.Encoding.utf8)!
        //路径
        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let filePath = path.appending("/data666.json")
        
        try! str.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8)
        
        print(filePath) //取件地址 点击桌面->前往->输入地址跳转取件
        
        return str
    }
} //注意这里还未对异常进行处理，只是方便大家转成JSON本地文件

//数组转JSON
func arrayToJson(_ array:NSMutableArray)->String{
    
    //首先判断能不能转换
    if (!JSONSerialization.isValidJSONObject(array)) {
        //print("is not a valid json object")
        return ""
    }
    
    //利用OC的json库转换成OC的NSData，
    //如果设置options为NSJSONWritingOptions.PrettyPrinted，则打印格式更好阅读
    let data : Data! = try? JSONSerialization.data(withJSONObject: array, options: [])
    //NSData转换成NSString打印输出
    let str = NSString(data:data, encoding: String.Encoding.utf8.rawValue)
    //输出json字符串
    return str! as String
}

//数组(里面类型为字典)转字符串
func dicArrayToJson(_ dicArray:[Dictionary<String,String>])->String{
    
    //首先判断能不能转换
    if (!JSONSerialization.isValidJSONObject(dicArray)) {
        //print("is not a valid json object")
        return ""
    }
    
    //利用OC的json库转换成OC的NSData，
    //如果设置options为NSJSONWritingOptions.PrettyPrinted，则打印格式更好阅读
    let data : Data! = try? JSONSerialization.data(withJSONObject: dicArray, options: [])
    //NSData转换成NSString打印输出
    let str = NSString(data:data, encoding: String.Encoding.utf8.rawValue)
    //输出json字符串
    return str! as String
}

/** json 字符串字典*/
func jsonToObject(jsonString:String)->Dictionary<String,NSObject>{
    
    let dic = Dictionary<String,NSObject>()
    
    
    do{
        
        let data = jsonString.data(using: String.Encoding.utf8)!
        //把NSData对象转换回JSON对象
        let json :Any! = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.mutableContainers)
        
        return json as! Dictionary<String, NSObject>
    }catch{
        return dic
    }
    
    
    
}

/** json 字符串 转数组*/
func jsonToArray(jsonString:String)->Array<Dictionary<String, String>>{
    
    let arr = [Dictionary<String,String>()]
    
    
    do{
        
        let data = jsonString.data(using: String.Encoding.utf8)!
        //把NSData对象转换回JSON对象
        let json : Any! = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.mutableContainers)
        
        return json as! [Dictionary<String, String>]
    }catch{
        return arr
    }
}


























